package org.stone.project.redis.utils;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.stone.project.redis.prop.CustomRedisProp;

@Component
public class RedisKeyUtil implements ApplicationContextAware {
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        customRedisProp = applicationContext.getBean(CustomRedisProp.class);
    }

    private static CustomRedisProp customRedisProp;


    /**
     * redis缓存key拼接
     * @param keyArry
     * @return
     */
    public static String concatRedsiKey(String prefix,String... keyArry){
        //缓存命名方式与cacheManager保持一致
        if (keyArry.length < 1){
            throw new IllegalArgumentException("缓存键值必须是两个字符串以上");
        }
        int arryLenth = keyArry.length;

        StringBuffer sb = new StringBuffer();
        sb.append(prefix).append(":");
        for (int i = 0; i < keyArry.length; i++) {
            String tmpStr = keyArry[i];
            if (ObjectUtil.isNull(tmpStr)){
                tmpStr = "null";
            }else if (ObjectUtil.isNull(tmpStr)){
                tmpStr = "";
            }

            sb.append(tmpStr);
            if (arryLenth >= 2){
                if (keyArry.length - 2 == i){
                    if (keyArry.length - 1 != i){
                        sb.append("::");
                    }
                }
                else if (keyArry.length - 1 != i){
                    sb.append(":");
                }
            }else {
                if (keyArry.length - 1 != i){
                    sb.append("::");
                }
            }
        }
        return sb.toString();
    }

    /**
     * redis缓存key拼接默认前缀
     * @param keyArry
     * @return
     */
    public static String concatRedisPrefixKey(String... keyArry){
        return concatRedsiKey(customRedisProp.getPrefix(),keyArry);
    }
}